package org.study.mybatis.generator.plugins;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.internal.util.StringUtility;
import org.mybatis.generator.internal.util.messages.Messages;
import org.mybatis.generator.plugins.RenameExampleClassPlugin;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义mybatis-generator插件：xxxMapper.java重命名
 * 参考 https://www.jianshu.com/p/b243f3ec8419
 * 参考 {@link RenameExampleClassPlugin}
 * <pre>
 * <plugin type="org.study.mybatis.generator.plugins.RenameJavaMapperPlugin">
 *     <property name="searchString" value="Mapper$" />
 *     <property name="replaceString" value="Dao" />
 * </plugin>
 * </pre>
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年12月09日
 */
public class RenameJavaMapperPlugin extends PluginAdapter {
    private String searchString;
    private String replaceString;
    private Pattern pattern;

    public boolean validate(List<String> warnings) {
        searchString = properties.getProperty("searchString");
        replaceString = properties.getProperty("replaceString");
        boolean valid = StringUtility.stringHasValue(searchString) && StringUtility.stringHasValue(replaceString);
        if (valid) {
            pattern = Pattern.compile(searchString);
        } else {
            if (!StringUtility.stringHasValue(searchString)) {
                warnings.add(Messages.getString("ValidationError.18", "RenameJavaMapperPlugin", "searchString"));
            }
            if (!StringUtility.stringHasValue(replaceString)) {
                warnings.add(Messages.getString("ValidationError.18", "RenameJavaMapperPlugin", "replaceString"));
            }
        }
        return valid;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        String oldType = introspectedTable.getMyBatis3JavaMapperType();
        Matcher matcher = pattern.matcher(oldType);
        oldType = matcher.replaceAll(replaceString);
        introspectedTable.setMyBatis3JavaMapperType(oldType);
    }
}
